package com.medusa.aps.business.config;

import com.medusa.aps.business.global.model.exception.GlobalException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
@Component
public class SqlContext {
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;


    public SqlSession getSqlSession() {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }


    public void rollback(Connection connection) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                log.error("事务回滚失败", e);
                throw new GlobalException("事务回滚失败");
            }
        }
    }

    public void close(Connection conn, SqlSession sqlSession) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            log.error("资源释放失败:", ex);
            throw new GlobalException("资源释放失败");
        }

        if (sqlSession != null) {
            sqlSession.close();
        }
    }

}